// 编写全局计算倒计通用逻辑

import { computed, onUnmounted, ref } from 'vue'

import dayjs from 'dayjs'
// 封装倒计时

export const useCountDown = () => {
    // 1.响应式数据
    let timer = null
    const Time = ref(0)
    // 进行格式化操作 xx分xx秒
    const formatTime = computed(() =>
        dayjs.unix(Time.value).format('mm分ss秒')
    )

    // 2.开启倒计时函数
    const start = (currentTime) => {
        // 开始倒计时逻辑
        // 核心逻辑:每隔一秒减一
        Time.value = currentTime
        setInterval(() => {
            Time.value--
        }, 1000)
    }
    // 组件销毁时，清除定时器
    onUnmounted(() => {
        timer && clearInterval(timer)
    })
    return {
        formatTime,
        start
    }
}